import requests
import threading
import cv2
import os
import json
import subprocess as sp 

def post_alarm(save_name,num_id,fun,alarmNumber,alarm_post_state):
    if fun=='cap':
        fun=1
    elif fun=='electric':
        fun=2
    elif fun=='gang':
        fun=3
    elif fun=='fire':
        fun=4
    elif fun=='burst':
        fun=5
    param      = {
                  'stream':str(num_id),
                  'alarmType':fun,#1火焰2安全帽
                  'deviceName':'deviceName1',#随意
                  'alarmNumber':alarmNumber,
                  'mp4Name':'123123',#时间+stream，移后
                  'img':save_name,#base64
                  'status':'2',#报警2
                  'post':str(alarm_post_state) #1为报警，2为记录
                  }
    req = json.dumps(param) #字典数据结构变json(所有程序语言都认识的字符串)
    res=requests.post('http://170.0.40.160:8080/foursteel/service/F_DU_AI_01', data=req)

def post_mp4(mp4_name,alarmNumber,num_id):
    param      = {
                  'stream':str(num_id),
                  'mp4Url':mp4_name,
                  'alarmNumber':alarmNumber,#时间+stream
                  }
    req = json.dumps(param) #字典数据结构变json(所有程序语言都认识的字符串)
    res=requests.post('http://170.0.40.160:8080/foursteel/service/F_DU_AI_03', data=req)



class Thread_ffmpeg_post(threading.Thread):#开启线程调用ffmepg转换格式并post
    def __init__(self,mp4_name,alarmNumber,num_id):
        threading.Thread.__init__(self)
        self.mp4_name = mp4_name
        self.alarmNumber = alarmNumber
        self.num_id=num_id
    def run(self):
        command = ['ffmpeg',
                    '-i', self.mp4_name,
                    '-strict', '-2',
                    '-vcodec', 'h264',
                    self.mp4_name[:-4]+'.mp4']
        pipe = sp.Popen(command, stdin=sp.PIPE) 
        pipe.wait() 
        post_mp4(self.mp4_name[:-4]+'.mp4',self.alarmNumber,self.num_id)

class Thread_post(threading.Thread):#开启线程post
    def __init__(self,id_stream,save_time,frame,model_fun,alarm_post_state,frame_ori):
        threading.Thread.__init__(self)
        self.id_stream = id_stream
        self.save_time = save_time
        self.frame=frame
        self.model_fun = model_fun#功能
        self.alarm_post_state = alarm_post_state #是报警还是记录
        self.frame_ori=frame_ori

    def run(self):
        date_time=self.save_time
        save_name=str(date_time.date())+'-'+str(date_time.hour)+'-'+str(date_time.minute)+'-'+str(date_time.second)+'.jpg'
        dirs = 'res_img/'+str(self.id_stream)
        if not os.path.exists(dirs):
            os.makedirs(dirs)
        cv2.imwrite(dirs+'/'+save_name,self.frame)
        dirs = 'ori_img/'+str(self.id_stream)
        if not os.path.exists(dirs):
            os.makedirs(dirs)
        cv2.imwrite(dirs+'/'+save_name,self.frame_ori)
        alarmNumber=str(date_time)+str(self.id_stream)
        post_alarm(save_name,self.id_stream,self.model_fun,alarmNumber,self.alarm_post_state)






